class Solution {
public:
    Node* copyRandomList(Node* head) {
        map<Node*, Node*> nodeMap;
        Node* copyhead = nullptr;
        Node* copytail = nullptr;
        Node* cur = head;
        while (cur) {
            if (copyhead == nullptr) {
                copytail = copyhead = new Node(cur->val);
            }
            else {
                copytail->next = new Node(cur->val);
                copytail = copytail->next;
            }
            nodeMap[cur] = copytail;
            cur = cur->next;
        }
        cur = head;
        Node* copy = copyhead;
        while (cur) {
            if (cur->random == nullptr) {
                copy->random = nullptr;
            }
            else {
                copy->random = nodeMap[cur->random];
            }
            cur = cur->next;
            copy = copy->next;
        }
        return copyhead;
    }
};